package master

import (
	"encoding/json"
	"log"
	"net"
	"net/http"
	"prepare/crontab/common"
	"strconv"
	"time"
)

// 任务的HTTP接口
type ApiSever struct {
	httpServer *http.Server
}

var (
	G_apiServer *ApiSever
)

func InitApiServer() (err error) {
	var (
		mux    *http.ServeMux
		listen net.Listener
		server *http.Server
	)
	// 配置路由
	mux = http.NewServeMux()
	mux.HandleFunc("/job/save", handleJobSave)

	// 启动TCP监听
	if listen, err = net.Listen("tcp", ":"+strconv.Itoa(G_config.ApiPort)); err != nil {
		return
	}

	// 创建一个Http服务
	server = &http.Server{
		ReadTimeout:  time.Duration(G_config.ApiReadTimeout) * time.Millisecond,
		WriteTimeout: time.Duration(G_config.ApiWriteTimeout) * time.Millisecond,
		Handler:      mux,
	}

	// 赋值单例
	G_apiServer = &ApiSever{
		httpServer: server,
	}

	// 启动服务端
	go server.Serve(listen)
	return
}

// 保存任务接口
// POST job={"name":"job1","command":"echo hello","cron_expr":"* * * * *"}
func handleJobSave(resp http.ResponseWriter, req *http.Request) {
	// 任务保存到etcd中
	var (
		err     error
		postJob string
		job     common.Job
		oldjob  *common.Job
		bytes   []byte
	)
	// 解析POST表单
	if err = req.ParseForm(); err != nil {
		goto ERR
	}

	// 取出表单中的job字段
	postJob = req.PostForm.Get("job")
	// 反序列化
	if err = json.Unmarshal([]byte(postJob), &job); err != nil {
		log.Println(err)
		goto ERR
	}

	// 保存到etcd
	if oldjob, err = G_jobMgr.SaveJob(&job); err != nil {
		log.Println(err)
		goto ERR
	}

	// 返回正确应答
	if bytes, err = common.BuildResponse(0, "success", oldjob); err == nil {
		resp.Write(bytes)
		return
	}
ERR:
	// 返回错误应答
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)

	}
	return
}
